﻿using System.Collections.Generic;
using UnityEngine;

namespace Framework
{
	public class ResLog
	{
		private static int Counter;
		public int counter = 0;
		public string path;
		public long size;
		public float loadTime;
		public float loadedTime;

		private string tostring;
		public bool needUpdate = false;

		public ResLog()
		{
			counter = Counter++;
		}
		public override string ToString()
		{
			if (needUpdate)
			{
				var cost = loadedTime > loadTime ? loadedTime - loadTime : -1;
				var costStr = string.Format("{0:F0}", cost * 1000) + "ms";
				var startStr = string.Format("{0:F2}", loadTime);
				var endStr = string.Format("{0:F2}", loadedTime);
				var sizeStr = string.Format("{0:F0}", size / 1024) + "kb";
				tostring = string.Format("cost:{0, -14}start:{1, -15}  end:{2, -15}  size:{3, -12}  {4, -128} ", costStr, startStr, endStr, sizeStr, path);
			}
			return tostring;
		}
	}

	public class ResLogMgr : Singleton<ResLogMgr>
	{
		private readonly Dictionary<string, ResLog> _logDict = new Dictionary<string, ResLog>();
		private readonly List<ResLog> _logList = new List<ResLog>();

		private bool _enable = false;
		public bool Enable
		{
			get => _enable;
			set => _enable = value;
		}

		public Dictionary<string, ResLog> GetDict()
		{
			return _logDict;
		}

		public List<ResLog> GetList()
		{
			return _logList;
		}

		public void Clear()
		{
			_logDict.Clear();
			_logList.Clear();
		}

		public void OnStartLoad(string path)
		{
			if (!Enable) return;
			ResLog log = null;
			_logDict.TryGetValue(path, out log);
			if (log == null)
			{
				log = new ResLog();
				log.path = path;
				_logDict.Add(path, log);
				_logList.Add(log);
			}
			log.loadTime = Time.time;
			log.needUpdate = true;
		}

		public void OnLoaded(string path, long size)
		{
			if (!Enable) return;
			ResLog log = null;
			_logDict.TryGetValue(path, out log);
			if (log == null)
			{
				log = new ResLog();
				log.path = path;
				_logDict.Add(path, log);
				_logList.Add(log);
			}
			log.loadedTime = Time.time;
			log.needUpdate = true;
			log.size = size;
		}
	}
}
